<template>
  <div class="container">
    <el-card class="box-card" shadow="always">
      <el-row :gutter="24">
        <el-col :span="14">
          <el-form inline @submit.native.prevent="search">
            <el-form-item label="搜索">
              <el-input
                v-model="searchForm.queryConditions"
                clearable
                placeholder="组织名/描述信息"
                prefix-icon="el-icon-search"
                size="medium"
              />
            </el-form-item>
            <el-form-item>
              <el-button native-type="submit" size="medium" type="primary">
                搜索
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="10">
          <el-button type="primary" icon="el-icon-download" class="btn">
            <a download :href="exportUrl"> 导出 </a>
          </el-button>
          <el-button
            type="danger"
            @click="deleteAllOrganization()"
            icon="el-icon-remove-outline"
            class="btn"
          >
            批量删除
          </el-button>
          <el-button
            type="primary"
            @click="addRoleDialog"
            icon="el-icon-circle-plus-outline"
            class="btn"
          >
            添加组织
          </el-button>
        </el-col>
      </el-row>

      <div>
        <el-table
          :data="list"
          border
          style="width: 100%"
          @selection-change="handleSelectChange"
          v-loading="organizeLoading"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            type="index"
            width="50"
            label="编号"
            align="center"
          />
          <el-table-column
            prop="organizeName"
            label="组织名称"
            align="center"
          />
          <el-table-column prop="description" label="组织描述" align="center" />
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-tooltip content="编辑组织信息" placement="top">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="editRoleDialog(scope.row)"
                />
              </el-tooltip>
              <el-tooltip content="删除组织" placement="top">
                <el-button
                  el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="deleteOrganization(scope.row)"
                />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          :current-page="paging.current"
          :page-sizes="paging.pageSizes"
          :page-size="paging.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paging.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <edit-dialog
        :index="index"
        :title="dialogTitle"
        :visible="editDialogVisible"
        :organization-info="OrganizationInfo"
        @cancel="cancel"
        @ok="ok"
      />
    </el-card>
  </div>
</template>

<script>
import {
  getAllOrganizationInfosByPageAndConditions, // 分页条件查询所有的组织信息
  deleteOrganizationInfo,
  addOrganizationInfo,
  updateOrganizationInfo,
  deleteOrganizationsInfo,
} from "@/api/organization";
import EditDialog from "./components/editDialog";
export default {
  name: "OrganizationManage",
  components: { EditDialog },
  data() {
    return {
      searchForm: {
        queryConditions: "",
      },
      //departmentList: [],
      list: [],
      multipleSelection: [], //复选框选中的所有数据
      paging: {
        total: 0,
        current: 1,
        pageSizes: [5, 10, 15],
        size: 5,
      },
      OrganizationInfo: {},
      editDialogVisible: false,
      organizeLoading: false,
      dialogTitle: "",
      index: 0, // 0 添加学生；1 编辑学生
      // headers: {
      //   token: localStorage.getItem("ds_token")
      // }
    };
  },
  computed: {
    exportUrl() {
      return process.env.VUE_APP_BASE_API + "/superManager/exportOrganizeExcel";
    },
    // uploadURL() {
    //   return process.env.VUE_APP_BASE_API + "/student/upload";
    // },
  },
  created() {
    this.organizeLoading = true;
    this.getData();
  },
  methods: {
    search() {
      this.paging.current = 1;
      this.organizeLoading = true;
      this.getData();
    },
    getData() {
      const form = {
        ...this.searchForm,
        page: this.paging.current,
        pageSize: this.paging.size,
      };
      getAllOrganizationInfosByPageAndConditions(form)
        .then((res) => {
          if (res.data) {
            this.list = res.data.organizations;
            // 返还每页显示的条数
            //this.paging.size = res.data.size;
            this.paging.total = res.data.totalCount;
            this.organizeLoading = false;
          }
        })
        .catch((err) => {
          // 如果没有数据就显示为空
          this.list = [];
          // 返还每页显示的条数
          //this.paging.size = res.data.size;
          this.paging.total = 0;
          this.organizeLoading = false;
        });
    },
    handleSizeChange(val) {
      this.paging.current = 1;
      this.paging.size = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.paging.current = val;
      this.getData();
    },
    // 获取到选中的所有数据
    handleSelectChange(val) {
      this.multipleSelection = [];
      val.forEach((value) => {
        this.multipleSelection.push(value.id);
      });

      console.log(this.multipleSelection);
    },
    deleteOrganization(row) {
      console.log(row.id);
      this.$confirm("此操作将永久删除这条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const result = await deleteOrganizationInfo({ id: row.id , accountId : this.$store.getters.accountId});
          console.log(result);
          if (result.code === 200) {
            this.$message({
              type: "success",
              message: "组织删除成功!请为原组织人员重新分配组织！",
            });
            this.getData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    deleteAllOrganization() {
      if (this.multipleSelection.length === 0) return;
      console.log(this.multipleSelection);
      this.$confirm("此操作将永久删除选中的数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const roleIds = this.multipleSelection.join(",");
          const result = await deleteOrganizationsInfo({ ids: roleIds, accountId : this.$store.getters.accountId});
          console.log(result);
          if (result.code === 200) {
            this.$message({
              type: "success",
              message: "成功删除" + result.data + "条数据!请为原组织人员重新分配组织！",
            });
            this.getData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    editRoleDialog(row) {
      this.dialogTitle = "编辑组织信息";
      this.editDialogVisible = true;
      this.OrganizationInfo = this.extendCopy(row);
      this.index = 1;
    },
    // 对象的深拷贝
    // 对象进行深拷贝，否则“编辑”框内修改内容也会影响到页面
    extendCopy(p) {
      var c = {};
      for (var i in p) { 
        c[i] = p[i];
      }
      return c;
    },
    addRoleDialog() {
      this.dialogTitle = "添加组织信息";
      this.editDialogVisible = true;
      this.index = 0;
    },
    cancel() {
      this.editDialogVisible = false;
      this.index = 0;
    },
    editOrganizationInfo(data) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        if (this.index) {
          // 编辑组织信息
          // console.log(val)
          const result = await updateOrganizationInfo(data);
          // console.log(res)
          if (result.code === 200) {
            this.$message.success("修改成功");
            resolve(result);
          } else {
            this.$message.error("修改失败，请重试");
            reject(result);
          }
        } else {
          const result = await addOrganizationInfo(data);
          // console.log(res)
          if (result.code === 200) {
            this.$message.success("添加成功");
            resolve(result);
          } else {
            this.$message.error("添加失败，请重试");
            reject(result);
          }
        }
      });
    },
    async ok(val) {
      const response = await this.editOrganizationInfo(val);
      console.log(response);
      if (response.code === 200) {
        this.editDialogVisible = false;
        this.getData();
        this.index = 0;
      }
    },
    handleSuccess(response, file, fileList) {
      console.log(response);
    },
  },
};
</script>

<style lang="scss" scoped>
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
.btn {
  float: right;
  margin-left: 20px;
}
</style>
